﻿
using Common;
using Microsoft.AspNetCore.Mvc;
using ModelDto;
using WebApplication1.Filter;

namespace WebApplication1.Controllers
{
    [ApiController]
    [ApiContentFilter]
    [Route("api/[controller]/[action]")]
    public class FileUploadController : ControllerBase
    {
        private readonly Ilog4netHelper _log;
        public FileUploadController(Ilog4netHelper log)
        {
            _log = log;
        }

        [HttpPost]
        public JsonResultL UploadFile()
        {
            DateTime now = DateTime.Now;
            JsonResultL response = new JsonResultL();
            //后缀名
            string extension = ",.txt,.rar,.zip,.jpg,.jpeg,.gif,.png,.swf,.wmv,.avi,.wma,.mp3,.xls,.xlsx,";

            var currentFile = HttpContext.Request.Form.Files[0];
            //var currentFile = HttpContext.Request.Form.Files.GetFile("file");
            if (currentFile == null)
            {
                return response.Fail("file文件未找到");
            }

            var CurrentExtension = Path.GetExtension(currentFile.FileName);
            if (extension.IndexOf($",{CurrentExtension},") < 0)
            {
                return response.Fail($"格式必须为：{extension}");
            }


            string path = $"{AppContext.BaseDirectory}wwwroot\\FileUrl\\Admin";

            Random rd = new Random();

            var temprd = rd.Next(10000, 99999);

            string pathFile = $"{now.ToString("yyyyMMddHHmmss")}{temprd}{CurrentExtension}";

            string resPath = $"/FileUrl/Admin/{pathFile}";

            var filePath = Path.Combine(path, pathFile);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            using (var stream = System.IO.File.Create(filePath))
            {
                currentFile.CopyTo(stream);
            };

            _log.Info($"返回路径：{resPath},保存路径：{filePath}");
            return response.Sucess(resPath);
        }
    }
}
